/**
 * 
 */
package com.wjk.web.book;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.wjk.domain.book.Book;
import com.wjk.service.book.BookService;

/**
 *
 * <br>
 *
 * @author wanjk@c-platform.com
 *
 *         <p>
 * @date 创建时间：2018年5月29日:下午11:59:43
 *       </p>
 *
 *       book controller
 */

@Controller
@RequestMapping(value = "/book")
public class BookController {

	private static final String BOOK_FORM_PATH_NAME = "bookForm";
	private static final String BOOK_LIST_PATH_NAME = "bookList";
	private static final String REDIRECT_TO_BOOK_URL = "redirect:/book";

	@Autowired
	BookService bookService;

	/**
	 * get book list
	 * 
	 * handle "/book"'s get request ,get book list
	 * 
	 * */
	@RequestMapping(method = RequestMethod.GET)
	public String getBookList(ModelMap map) {
		map.addAttribute("bookList", bookService.findAll());
		return BOOK_LIST_PATH_NAME;
	}

	/**
	 * get book form
	 * 
	 */
	@RequestMapping(value = "/create", method = RequestMethod.GET)
	public String createBookForm(ModelMap map) {
		map.addAttribute("book", new Book());
		map.addAttribute("action", "create");
		return BOOK_FORM_PATH_NAME;
	}

	/**
	 * 创建 Book 处理 "/book/create" 的 POST 请求，用来新建 Book 信息 通过 @ModelAttribute
	 * 绑定表单实体参数，也通过 @RequestParam 传递参数
	 */
	@RequestMapping(value = "/create", method = RequestMethod.POST)
	public String postBook(@ModelAttribute Book book) {
		bookService.insertByBook(book);
		return REDIRECT_TO_BOOK_URL;
	}

    /**
     * 获取更新 Book 表单
     *    处理 "/book/update/{id}" 的 GET 请求，通过 URL 中的 id 值获取 Book 信息
     *    URL 中的 id ，通过 @PathVariable 绑定参数
     */
    @RequestMapping(value = "/update/{id}", method = RequestMethod.GET)
    public String getUser(@PathVariable Long id, ModelMap map) {
        map.addAttribute("book", bookService.findById(id));
        map.addAttribute("action", "update");
        return BOOK_FORM_PATH_NAME;
    }
    /**
     * 更新 Book
     * 处理 "/update" 的 PUT 请求，用来更新 Book 信息
     */
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public String putBook(@ModelAttribute Book book) {
        bookService.update(book);
        return REDIRECT_TO_BOOK_URL;
    }

    /**
     * 删除 Book
     * 处理 "/book/{id}" 的 GET 请求，用来删除 Book 信息
     */
    @RequestMapping(value = "/delete/{id}", method = RequestMethod.GET)
    public String deleteBook(@PathVariable Long id) {
    	Book book = new Book();
    	book.setId(id);
        bookService.delete(book);
        return REDIRECT_TO_BOOK_URL;
    }

	
}
